package com.baichang.taoshunda.service.impl;


import com.baichang.framework.excelption.ServiceException;
import com.baichang.taoshunda.dao.ScoreDao;
import com.baichang.taoshunda.entity.Score;
import com.baichang.taoshunda.service.ParamsService;
import com.baichang.taoshunda.service.ScoreListService;
import com.baichang.taoshunda.service.ScoreService;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;

/**
 * Created by ${wushenglu} on 2017/8/17 0017.
 */
@Service
public class ScoreServiceImpl implements ScoreService {
    @Autowired
    private ScoreDao scoreDao;
    @Autowired
    private ParamsService paramsService;
    @Autowired
    private ScoreListService scoreListService;


    /**
     * 添加积分
     *
     * @param point  积分
     * @param userId 用户编号
     * @return
     */
    @Override
    public boolean addScore(int point, int userId) {
        Score score = new Score();
        //创建时间
        score.setCreated(new Date());
        //分数
        score.setScore(point);
        //用户编号
        score.setUserId(userId);
        return scoreDao.save(score) > 0;
    }

    /**
     * 根据用户编号和积分获取类型添加用户积分
     *
     * @param typeId 积分添加类型 1签到2分享
     * @param userId 用户编号
     * @return
     */
    @Override
    public boolean addScoreByType(int typeId, int userId) throws ServiceException {
        int point;
        int paramsId = 0;
        int scoreSum = 0;
        //参数类型
        int paramsType = 2;
        String source = null;
        //签到
        if (typeId == 1) {
            source = "签到";
            //参数编号
            paramsId = 4;
            int count = scoreListService.getTodayCount(userId);
            if (count > 0) {
                throw new ServiceException("今日已签到");
            }
            //分享
        } else if (typeId == 2) {
            paramsId = 20;
            source = "分享";
            scoreSum = scoreDao.getScoreSumByUserId(userId);
        }
        Map<String, Object> score = paramsService.getParamsValue(paramsType, paramsId);
        //获取积分
        point = Integer.parseInt(score.get("value").toString());
        if (scoreSum < 10) {
            boolean flag = scoreDao.addScoreByType(point, userId);
            if (flag) {
                //添加积分详细
                scoreListService.addScoreList(point, userId, source);
            }
            return flag;
        }
        return false;

    }

    @Override
    public Map<String, Object> getStateAndScore(int userId) {
        Map<String, Object> map = new HashedMap();
        map.put("score", scoreDao.getScoreByUserId(userId));
        Map<String, Object> score = paramsService.getParamsValue(2, 4);
        int point = Integer.parseInt(score.get("value").toString());
        map.put("addScore", point);
        map.put("state", scoreListService.getTodayCount(userId));
        return map;
    }

}
